<template>
  <div class="qr-code-component">
    <div class="qr-code-row">
      <div v-if="qrCodeData" class="qr-code-container">
        <img :src="qrCodeData.qrCodeImgUrl" alt="二维码" class="qr-code-image" @click="openPreview($event)" style="cursor: pointer;" />
      </div>
      <div v-else class="qr-code-loading">
        正在加载二维码...
      </div>
    </div>
    <button class="refresh-btn" @click="refreshQrCode">刷新二维码</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { showImagePreview } from 'vant';

const props = defineProps({
  apiFunction: {
    type: Function,
    required: true
  },
  title: {
    type: String,
    default: '扫描二维码'
  }
});

const emit = defineEmits(['qrCodeLoaded']);

const qrCodeData = ref(null);

onMounted(() => {
  getQrCode();
});

const getQrCode = async () => {
  try {
    const response = await props.apiFunction();
    if (response.code === 200) {
      qrCodeData.value = response.data;
      emit('qrCodeLoaded', response.data);
    }
  } catch (error) {
    console.error('获取二维码失败:', error);
  }
};

const refreshQrCode = () => {
  qrCodeData.value = null;
  getQrCode();
};

// 预览二维码
const openPreview = (event) => {
  const imgElement = event.target;
  const imgUrl = imgElement.src;
  
  showImagePreview({
    images: [imgUrl],
    startPosition: 0,
    closeable: true,
    closeIconPosition: 'top-right',
  });
};
</script>

<style scoped>
.qr-code-component {
  margin: 15px 0;
}

.qr-code-row {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 15px;
}

.qr-code-container {
  display: flex;
  align-items: center;
  overflow: hidden;
  border-radius: 8px;
}

.qr-code-image {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  border: 1px solid #eee;
  background: #fafbfc;
  object-fit: contain;
  transition: all 0.3s ease-in-out;
  transform-origin: center;
  cursor: pointer;
}

.qr-code-image:hover {
  transform: scale(1.04);
  border-color: #007bff;
  box-shadow: 0 6px 16px rgba(0,107,255,0.15);
}

.refresh-btn {
  height: 36px;
  padding: 0 18px;
  background: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  outline: none;
}

.refresh-btn:hover {
  background: #0056b3;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.qr-code-loading {
  color: #888;
  font-size: 15px;
  padding: 24px 0;
}
</style> 